<template>
  <div class="app-container">
    <div>
      <!-- 查询 -->
      <el-form :inline="true" class="search-form" label-width="50px">
        <el-row style="display: flex">
          <div style="flex: 1">
            <el-form-item label="名称" style="margin: 5px 0">
              <el-input
                v-model="query.name"
                class="filter-item"
                placeholder="请输入名称"
                clearable
              />
            </el-form-item>
          </div>
          <div style="margin: 5px 0">
            <el-form-item>
              <el-button
                class=""
                type="primary"
                icon="el-icon-search"
                @click="search"
                >查询</el-button
              >
              <el-button
                class=""
                size="small"
                type="primary"
                icon="el-icon-refresh"
                @click="refresh()"
                >重置</el-button
              >
            </el-form-item>
          </div>
        </el-row>
      </el-form>

    </div>
    <el-divider></el-divider>
    <div class="marginTop">
      <el-row :gutter="0">
        <el-col>
          <el-button
            class=""
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="add()"
            >添加省份</el-button
          >
        </el-col>
        <el-col class="marginTop">
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="datas"
            :header-cell-style="{
              'background-color': '#f3f8fe',
              color: '#606266',
              height: '50px',
            }"
            :max-height="height"
            style="width: 100%"
            row-key="id"
            lazy
            :load="listLoad"
            @sort-change="sorting"
          >
            <el-table-column
              prop="name"
              label="名称"
              min-width="140"
              align="left"
            />
            <el-table-column
              prop="area_code"
              label="行政代码"
              min-width="160"
              align="center"
              sortable="custom"
            />
            <el-table-column
              prop="zip_code"
              label="邮政编码"
              min-width="80"
              align="center"
              sortable="custom"
            />
            <el-table-column
              prop="city_code"
              label="区号"
              min-width="60"
              align="center"
              sortable="custom"
            />
            <el-table-column
              prop="level"
              label="级别"
              min-width="75"
              align="center"
              sortable="custom"
            />
            <el-table-column
              label="操作"
              min-width="120"
              align="center"
              fixed="right"
            >
              <template slot-scope="{ row }">
                <el-button type="primary" size="mini" @click="edit(row)"
                  >编辑</el-button
                >
                <el-button type="danger" size="mini" @click="del(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <!-- 列表 -->

    <!-- 添加、修改 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      top="10vh"
      width="700px"
      :close-on-click-modal="false"
      :before-close="cancel"
    >
      <el-row style="position: relative" v-loading="dialogLoading">
        <el-form
          ref="formRef"
          :rules="rules"
          :model="model"
          class=""
          label-width="100px"
        >
          <el-col :span="11">
            <el-form-item label="父级" prop="parent_code">
              <el-cascader
                disabled
                v-model="model.parent_code"
                :options="regionTree"
                :props="regionProps"
                clearable
                filterable
                placeholder="一级地区"
                style="width: 100%"
                @change="pickParentCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="名称" prop="name">
              <el-input
                v-model="model.name"
                placeholder="请输入名称：北京市"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="简称" prop="short_name">
              <el-input v-model="model.short_name" placeholder="" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="拼音" prop="pinyin">
              <el-input v-model="model.pinyin" placeholder="" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="行政代码" prop="area_code">
              <el-input
                disabled
                v-model="model.area_code"
                placeholder="请输入编码：110000"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="邮政编码" prop="zip_code">
              <el-input v-model="model.zip_code" placeholder="" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="区号" prop="city_code">
              <el-input
                disabled
                v-model="model.city_code"
                placeholder=""
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="经度" prop="lng">
              <el-input disabled v-model="model.lng" placeholder="" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="纬度" prop="lat">
              <el-input disabled v-model="model.lat" placeholder="" clearable />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="dialogLoading" type="primary" @click="submit"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from "@/utils/screen-height";
import Pagination from "@/components/Pagination";
import { disabledTree } from "@/utils/index";
import { list, info, save, del, tree } from "@/api/admin/region";

export default {
  name: "AdminRegion",
  components: { Pagination },
  data() {
    return {
      height: 680,
      loading: false,
      datas: [],
      query: {},
      dialogVisible: false,
      dialogTitle: "",
      btnLoading: false,
      model: {
        id: "",
        parent_code: "",
        area_code: "",
        zip_code: "",
        city_code: "",
        name: "",
        short_name: "",
        pinyin: "",
        lng: "",
        lat: "",
        level: "",
        sorting: 100,
        status: "",
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        area_code: [
          { required: true, message: "请输入行政代码", trigger: "blur" },
        ],
      },

      regionTree: [],
      regionProps: {
        expandTrigger: "click",
        checkStrictly: true,
        value: "area_code",
        label: "name",
      },
      dialogLoading: false,
    };
  },
  created() {
    this.height = screenHeight();
    this.list();
  },
  methods: {
    // 列表
    list() {
      this.loading = true;
      list(this.query)
        .then((res) => {
          this.datas = res.data.data;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 树形列表
    tree(row) {
      console.log(111);
      this.dialogLoading = true;
      this.regionTree = [];
      tree({})
        .then((res) => {
          this.dialogLoading = false;
          if (row) {
            this.regionTree = disabledTree(res.data.data, row.id);
          } else {
            this.regionTree = res.data.data;
          }
        })
        .catch(() => {});
    },
    // 添加
    add(row) {
      this.dialogVisible = true;
      this.dialogTitle = "新增";
      this.tree();
      if (row) {
        this.model = this.$options.data().model;
        this.model.parent_code = row.area_code;
      } else {
        this.reset();
      }
    },
    // 修改
    edit(row) {
      console.log(row);
      this.dialogVisible = true;
      this.dialogLoading = true;
      this.dialogTitle = "编辑：" + row.name;
      this.tree(row);
      info({
        id: row.id,
      }).then((res) => {
        this.model = res.data;
      });
    },
    // 删除
    del(row) {
      this.$confirm(
        '确定要删除ID： <span style="color:red">' +
          row.name +
          " </span> 这条数据吗？",
        "名称：" + row.name,
        { type: "warning", dangerouslyUseHTMLString: true }
      )
        .then(() => {
          this.loading = true;
          del({
            id: row.id,
          })
            .then((res) => {
              this.list();
              this.reset();
              this.$messages.success(res.msg);
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    // 取消
    cancel() {
      this.dialogVisible = false;
      this.reset();
    },
    // 提交
    submit() {
      this.$refs["formRef"].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          this.dialogVisible = true;
          this.model.parent_code = this.getParentId(this.model.parent_code);
          save(this.model, "post")
            .then((res) => {
              this.btnLoading = false;
              if (res.code !== 200 || res.status !== 1) {
                return this.$messages.error(res.msg);
              }
              this.btnLoading = false;
              this.dialogVisible = false;
              this.list();
              this.reset();
              this.dialogVisible = false;
              this.$messages.success(res.msg);
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row;
      } else {
        this.model = this.$options.data().model;
      }
      if (this.$refs["formRef"] !== undefined) {
        this.$refs["formRef"].resetFields();
      }
    },
    // 查询
    search() {
      this.query.page = 1;
      this.list();
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query;
      this.list();
    },
    // 排序
    sorting(sort) {
      this.query.sort_field = sort.prop;
      this.query.sort_value = "";
      if (sort.order === "ascending") {
        this.query.sort_value = "asc";
        this.list();
      }
      if (sort.order === "descending") {
        this.query.sort_value = "desc";
        this.list();
      }
    },

    // 懒加载
    listLoad(tree, treeNode, resolve) {
      list({
        parent_code: tree.area_code,
      }).then((res) => {
        resolve(res.data.data);
      });
    },
    // 父级选择
    pickParentCode(value) {
      if (value) {
        //this.model.parent_id = this.getParentId(value)
      }
    },
    getParentId(ids) {
      if (Array.isArray(ids)) {
        // 取数组最后一项的值
        return ids[ids.length - 1];
      } else {
        return ids;
      }
    },
  },
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
